<script setup lang="ts">
  import appConfig from '@/config/app'
import { addWeChatBefore, getAuthorize, getPlan, getUnionId,getQrPick } from '@/api/modules/ad';
import { onMounted, reactive, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import phoneForm from '@/components/phoneForm.vue';
import footerForm from '@/components/footerForm.vue';
import bgSubmit from '@/components/bgSubmit.vue';
import countdown from '@/components/countdown.vue';
import groupBuying from '@/components/groupBuying.vue';
import groupBtn from '@/components/groupBtn.vue';
import questionnaire from '@/components/questionnaire.vue';
// 导入平台检测工具
import { isWeChatBrowser, isWeChatMiniProgram } from '@/utils/platform';
const route = useRoute()
const formRef = ref();
const sendData:any = ref(null);
//是否显示问卷
const qs=reactive({
  isShow:false
})
//微信下使用
const jv=reactive({
  isJV:false,
  isHeader:true,
  unionId:'',
  er:''
})
const des = reactive({
  html:'',//正文
  headerImageUrl:'',//头图
  qrcodeAreaBgUrl:'',//二维码背景图
  isShowForm:false, //是否先留资
  wechatFlowCode:'', //模式
  courseId:'', //课程id
  courseCode:'',//课程编码
  schemeCode:'',//小程序连接
  templateInfo:{} as any,//模板样式
})
//获客助手前置接口
const weChatBefore=async (data?:any)=>{
  const option:any={
    ...route.query,
    source:route.query?.source,  //投放渠道
    planCode:route.query?.p_id,//计划id
    landingUrl:window.location.href,//原始落地页 URL（含追踪参数，如 bd_vid）
    requestCode:data?.requestCode||'',
    customerAssistantFlag:false, //是否使用获客助手
  }
  const bRes=await addWeChatBefore(option)
  if(bRes.code===0){
    sendData.value=bRes?.data
  }
}
/**
 * 获取计划详情
 * standard_price_template:标准模板(含价格)
 * standard_noprice_template:标准模板(不含价格)
 * front_bg_template:前置背景图模板
 * countdown_template:倒计时模板
 * postposition_questionnaire_template:后置问卷模板
 * group_template:团购模板
 */
const getDes = async () => {
  const res = await getPlan(route.query.p_id)
  if(res.code === 0){
    window.document.title=res?.data?.landingTemplate?.deliveryLandingTemplateName||'书芽'
    //判断是否是团购模板
    des.html = res?.data?.landingTemplate?.contentHtml
    des.headerImageUrl=res?.data?.landingTemplate?.startUrl+res?.data?.landingTemplate?.headerImageUrl;
    des.qrcodeAreaBgUrl=res?.data?.landingTemplate?.startUrl+res?.data?.landingTemplate?.qrcodeAreaBgUrl;
    des.isShowForm=['H5_INFO_XCX_INFO_V','H5_INFO_SIDE_V'].includes(res?.data?.wechatFlowCode)
    des.wechatFlowCode=res?.data?.wechatFlowCode;
    des.courseId=res?.data?.courseId;
    des.schemeCode=res?.data?.schemeCode;
    des.courseCode=res?.data?.courseCode;
    des.templateInfo=res?.data?.landingTemplate||{}
    //不留资,使用获客助手
    if(res?.data?.wechatFlowCode=='H5_NO_AIDE_V'){
      weChatBefore()
    }
    //自动跳转，且不在微信里
    if(res.data.redirectType===1){
      if(!isWeChatBrowser()&&!isWeChatMiniProgram()){
        goToNext()
      }
    }
    
  }
  const qrRes=await getQrPick({
    planCode:route.query?.p_id,//计划id
  })
  if(qrRes.code===0){
    jv.er=qrRes?.data
  }
}
//服务端获取unionId
const getWxInfo=async ()=>{
  //微信内，需要获取授权信息
  if(!route.query?.code){
    const res=await getAuthorize({
      redirectUrl:window.location.href,
      state:'STATE',
    })
    if(res.code===0){
      window.location.href=res?.data
    }
  }else{
    if(localStorage.getItem(appConfig.TOKENNAME)){
      const userInfo=JSON.parse(localStorage.getItem('userInfo')||'{}')
      jv.unionId=userInfo?.wechatUnionId||''
    }else{
      const res=await getUnionId({
        code:route.query?.code,
        type:'serve'
      })
      jv.unionId=res?.data?.unionId
    }
    
  }
  
}
onMounted(async ()=>{
  if(isWeChatBrowser()){
    await getWxInfo()
  }
  await getDes()
})

// 监听问卷显示状态，控制页面滚动
watch(() => qs.isShow, (newVal) => {
  if (newVal) {
    // 禁止页面滚动
    document.body.style.overflow = 'hidden';
    document.body.style.position = 'fixed';
    document.body.style.width = '100%';
  } else {
    // 恢复页面滚动
    document.body.style.overflow = '';
    document.body.style.position = '';
    document.body.style.width = '';
  }
});
//点击跳转，一种是留资后（留资需要请求加V前接口），一种不留资后
const goToNext=async (data?:any)=>{
  if(des.templateInfo?.templateStyle=='postposition_questionnaire_template'&&!qs.isShow){
    qs.isShow=true
    return
  }
  // window.open(`weixin://biz/ww/profile/${encodeURIComponent('https://work.weixin.qq.com/ca/cawcde57f0274d9006?customer_channel=baidu_YELXNPbN_8')}`)
  let url=des.schemeCode;
  //小程序留资，需要跳转详情页
  //weixin://dl/business/?t=tFHnP8jq3xn&cq=user_id=12345
  if(['H5_NO_XCX_INFO_V','H5_INFO_XCX_INFO_V','H5_NO_XCX_V'].includes(des.wechatFlowCode)){
    //把url参数带到小程序里,ll是流量分类
    let urlPar=`${window.location.search.replace('?','')}&ll=${route.params?.id||''}&rc=${data?.requestCode||''}`.replace(/&/g,'/').replace(/=/g,'~')
    url+=`&cq=web=${urlPar}`
    console.log(url)
  }
  if(isWeChatBrowser()||isWeChatMiniProgram()){
    // 微信浏览器或小程序内
    jv.isJV=true
    jv.isHeader=true
    //公众号和小程序内加V前，需要调用接口
    await addWeChatBefore({
      wxUnionId:jv.unionId||route.query?.unionId||'',
      source:route.query?.source,  //投放渠道
      planCode:route.query?.p_id,//计划id
      landingUrl:window.location.href,
      requestCode:data?.requestCode||'',
      customerAssistantFlag:false
    })
  }else{
    //获客助手加V
    if(des.wechatFlowCode && ['H5_INFO_SIDE_V','H5_NO_AIDE_V'].includes(des.wechatFlowCode)){
      //需要先留资，再加v
      if(des.wechatFlowCode==='H5_INFO_SIDE_V'){
        await weChatBefore(data)
      }
      //渠道_课程_投放计划_code
      // const temp=[des.courseId,route.query?.source,route.query?.p_id,sendData.value?.requestCode]
      const temp=[sendData.value?.requestCode]
      window.location.href=`weixin://biz/ww/profile/${encodeURIComponent(`https://work.weixin.qq.com/ca/cawcde57f0274d9006?customer_channel=${temp.join('_')}`)}`
    }else{
      //跳转小程序
      window.location.href=url;
    }
  }  
}
const submit=()=>{
  if(des.isShowForm){
    formRef.value?.submit()
  }else{
    goToNext()
  }
}
</script>

<template>
  <div class="home">
    <div v-if="des.templateInfo?.templateStyle!='front_bg_template'">
      <div class="c">
        <p><img :src="des.headerImageUrl" style="box-sizing: border-box; border: 0px; vertical-align: middle;"></p>
      </div>
      <groupBuying v-if="des.templateInfo?.templateStyle=='group_template'" @submit="submit"/>
      <phoneForm v-if="des.isShowForm" ref="formRef" :templateInfo="des.templateInfo" @goToNext="goToNext" />
      <div class="c" v-html="des.html"></div>

      <countdown v-if="des.templateInfo?.templateStyle=='countdown_template'" @submit="submit" :templateInfo="des.templateInfo"/>
      <footerForm v-if="['standard_price_template','standard_noprice_template','postposition_questionnaire_template'].includes(des.templateInfo?.templateStyle)" @submit="submit" :templateInfo="des.templateInfo"/>
      <groupBtn v-if="des.templateInfo?.templateStyle=='group_template'" @submit="submit" :templateInfo="des.templateInfo"/>
    </div>
    <div v-if="des.templateInfo?.templateStyle=='front_bg_template'" class="bg_temp" :style="`background: url(${des?.headerImageUrl}) no-repeat top center; background-size: 100% 100%;`">
        <bgSubmit @submit="submit" :templateInfo="des.templateInfo"/>
    </div>

    <div v-if="jv.isJV" class="jv">
      <div v-if="jv.isHeader" class="h">
        <div class="d">
          <img src="/img/d.png" mode="aspectFit"></img>
          <span>此二维码已通过安全验证，可以放心扫描</span>
        </div>
        <div class="close" @click="jv.isHeader=false">
          <img src="/img/c.png" mode="aspectFit"></img>
        </div>
      </div>
      <div class="jc" :style="`background: url(${des.qrcodeAreaBgUrl||'/img/er.png'}) no-repeat top center; background-size: 100% auto;`">
        <img :src="jv.er" mode="aspectFit"></img>
      </div>
      <div class="k-h">课程编号：{{ des.courseCode }}</div>
      <div class="k-b">课程编号：{{ des.courseCode }}</div>
    </div>
    <questionnaire v-if="qs.isShow&&des.templateInfo?.toolHomeworkId" @submit="submit"  :templateInfo="des.templateInfo"/>
  </div>
</template>

<style scoped lang="scss">
.home {
  max-width: 100%;
  .df{
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .c {
    max-width: 100%;
    /* 深度选择器确保样式能应用到v-html内容 */
    :deep(img) {
      width: 100% !important;
      height: auto !important;
      display: block !important;
      max-width: 100% !important;
    }
    :deep(p) {
      text-align: justify;
      margin: 0;
      padding: 0;
      margin-bottom: 0 !important;
      :deep(img) {
        width: 100% !important;
        height: auto !important;
      }
    }
  }
  .jv{
		width: 100vw;
		height: 100vh;
		background: rgba(0, 0, 0, 0.8);
		position: fixed;
    left: 0;
    top: 0;
    z-index: 50;
    .h{
      background: #F1FEFA;
      height: 1.2rem;
      position: absolute;
      z-index: 100;
      left: 0;
      top: 0;
      right: 0;
      color: #01E66F;
      font-size: 0.42rem;
      line-height: 1.2rem;
      display: flex;
      flex-direction: row;
      .d{
        flex: 1;
        padding-left: 0.2rem;
        img{
          width: 0.52rem;
          height: 0.52rem;
          margin-right: 0.1rem;
          vertical-align:sub;
        }
      }
      .close{
        margin-right: 0.2rem;
        img{
          width: 0.52rem;
          height: 0.52rem;
          vertical-align:sub;
        }
      }
    }
    .jc{
      width: 70%;
      min-height: 10rem;
      background-color: #fff;
      position: absolute;
      left: 15%;
      top: 50%;
      margin-top: -5rem;
      img{
        width: 4rem;
        height: 4rem;
        position: relative;
        left: 50%;
        top: 4rem;
        margin-left: -2rem;
      }
    }
    .k-h,.k-b{
      font-size: 0.3rem;
      line-height: 0.64rem;
      color: #fff;
      z-index: 100;
      position: absolute;
    }
    .k-h{
      top: 1.2rem;
      left: 0.3rem;
    }
    .k-b{
      bottom: 0.2rem;
      right: 0.3rem;
    }
	}

  .bg_temp{
    width: 100vw;
    height: 100vh;
  }
}

</style>